<?php


namespace app\services\user;


use app\models\user\DetailedGreenScoresModel;
use app\models\user\UserModel;
use app\services\BaseService;
use think\facade\Db;

//绿色积分
class DetailedGreenScoresService extends BaseService
{

    const ORDER = 1;
    const ADMIN_ADD = 4;
    const SIGN_IN = 5;

    const DIRECT_PUSH = 6;

    const REWARD = 7;

    const REDEMPTION = 101;
    const ADMIN_REDUCE = 102;

    const CONVERT_BALANCE = 103;


    protected static $typeArr = [

        self::ADMIN_ADD => '管理员增加',
        self::ORDER => '订单商品赠送积分',
        self::SIGN_IN => '签到赠送积分',
        self::DIRECT_PUSH => '直推赠送积分',
        self::REWARD => '推广奖励积分',

        //积分减少
        self::REDEMPTION => '订单退款扣除',
        self::ADMIN_REDUCE => '管理员扣除',
        self::CONVERT_BALANCE => '绿色积分转消费积分',
    ];

    protected static function initModel()
    {
        return new DetailedGreenScoresModel();
    }

    public static function getTypeArr()
    {
        return self::$typeArr;
    }

    public static function getTypeText($key)
    {
        $arr = self::$typeArr;
        return isset($arr[$key]) ? $arr[$key] : '未知类型';
    }

    /**
     * 添加余额变更记录
     * @param $userId
     * @param $type
     * @param $amount
     * @param $relatedUid
     * @param $orderSn
     * @param $remark
     * @return bool
     * @throws \Exception
     */
    public static function create($userId, $type, $amount, $orderSn = '', $relatedUid = 0, $remark = '')
    {
        try {
            $userInfo = UserModel::find($userId);
            if (!$userInfo) {
                return true;
            }
            $before = $userInfo['green_scores'];
            if ($type < 100) {
                $after = $before + $amount;
                //累计积分
                //$userInfo->total_green_scores = $userInfo->green_scores + $amount;
            } else {
                if ($before < $amount) {
                    throw new \Exception('用户绿色积分余额不足');
                }
                $after = $before - $amount;
            }
            $userInfo->green_scores = $after;
            $userInfo->save();
            return self::initModel()->save([
                'user_id' => $userId,
                'type' => $type,
                'before' => $before,
                'amount' => $amount,
                'after' => $after,
                'related_uid' => $relatedUid,
                'order_sn' => $orderSn,
                'remark' => $remark ? $remark : self::getTypeText($type),
            ]);
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }



    public static function upgrade($amount,$level_id){
        $id = UserLevelModel::where('amount','<',$amount)->order('amount','desc')->value('id');
        if($id != $level_id){
            return $id;
        }
        return false;
    }
}